﻿using FastCode.DTO;
using FastCode.Helper;
using FastCode.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;
using System.Security.Claims;

namespace FastCode.Architecture
{

    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ApiControllerBase<TEntity> : ControllerBase where TEntity : BaseModel, new()
    {
        protected ISqlSugarClient db;
        protected string? CurrentUsername => User.FindFirst(ClaimTypes.Name)?.Value;
        protected string? CurrentUserId => User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

        public ApiControllerBase(ISqlSugarClient _db)
        {
            db = _db;
        }


        public ISugarQueryable<BEntity> GetBaseQuery<BEntity>() where BEntity : BaseModel
        {
            return db.Queryable<BEntity>().Where(x => !x.IsDeleted);
        }


        [HttpPost]
        public virtual async Task<object> List([FromBody] QueryBase queryBase)
        {
            RefAsync<int> totalNumber = 0;

            var query = db.Queryable<TEntity>().Where(x => !x.IsDeleted);

            // 解析 SearchCondition 并构建查询条件
            if (queryBase.SearchConditions != null && queryBase.SearchConditions.Any())
            {
                //var searchConditions = JsonConvert.DeserializeObject<List<SearchCondition>>(queryBase.SearchCondition);
                foreach (var searchConditions in queryBase.SearchConditions)
                {
                    foreach (var condition in searchConditions.ConditionalModels)
                    {
                        if (!condition.FieldValue.IsHasValue())
                        {
                            continue;
                        }

                        if (condition.FieldName.EndsWith(ConstData.SplitStart))
                        {
                            condition.FieldName = condition.FieldName.Replace(ConstData.SplitStart, string.Empty);
                        }
                        else if (condition.FieldName.EndsWith(ConstData.SplitEnd))
                        {
                            condition.FieldName = condition.FieldName.Replace(ConstData.SplitEnd, string.Empty);
                        }
                        query = query.Where(new List<IConditionalModel>() { condition });
                    }
                }
            }
            var list = await query.ToPageListAsync(queryBase.pageIndex, queryBase.pageSize, totalNumber);

            var columnNames = new List<ColumnConfig>();
            //获取并返回对象的所有属性名
            Type entityType = typeof(TEntity);
            PropertyInfo[] properties = entityType.GetProperties();
            //foreach (PropertyInfo property in properties)
            //{
            //    GenerageCodeHelper.SetColumnConfig(property, columnNames);
            //}

            return Msg.Success(new { list, columnNames = columnNames.OrderBy(x => x.Order), totalNumber = totalNumber.Value });
        }
      

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<object> GetAllData()
        {
            var query = GetBaseQuery<TEntity>();
            var list = await query.ToListAsync();
            return Msg.Success(list);
        }


        [HttpPost]
        public async Task<object> DelById([FromBody] TEntity query)
        {
            var findItem = await db.Queryable<TEntity>().FirstAsync(x => x.Id == query.Id);

            return Msg.Success(findItem);
        }


        [HttpPost]
        public async Task<object> GetById([FromBody] TEntity query)
        {
            var findItem = await db.Queryable<TEntity>().FirstAsync(x => x.Id == query.Id);

            return Msg.Success(findItem);
        }

        [HttpPost]
        public virtual async Task<object> Update([FromBody] TEntity entity)
        {
            try
            {
                if (entity == null)
                {
                    return Msg.Error("传入数据为空");
                }

                var nowTime = DateTime.Now;
                
                if (entity.Id == 0)
                {
                    // 新增：设置创建时间
                    entity.CreateTime = nowTime;
                    entity.UpdateTime = null;
                    await db.Insertable(entity).ExecuteCommandAsync();
                    return Msg.Success(message: "新增成功");
                }
                else
                {
                    // 更新：设置更新时间
                    entity.UpdateTime = nowTime;
                    await db.Updateable(entity).ExecuteCommandAsync();
                    return Msg.Success(message: "更新成功");
                }
            }
            catch (Exception ex)
            {
                return Msg.Error($"操作失败: {ex.Message}");
            }
        }

        ///// <summary>
        ///// 校验非空数据是否填写
        ///// </summary>
        ///// <returns></returns>
        //public bool ValidNonNullData<T>(T entity, out string errMsg)
        //{
        //    errMsg = string.Empty;
        //    if (entity == null)
        //    {
        //        errMsg = "传入数据为空";
        //        return false;
        //    }

        //    // 获取 CarrierDTO 类型的所有公共属性
        //    var properties = typeof(T).GetProperties();

        //    NullabilityInfoContext nullabilityContext = new NullabilityInfoContext();
        //    // 遍历所有属性
        //    foreach (var property in properties)
        //    {
        //        //允许类为空
        //        if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
        //        {
        //            continue;
        //        }
        //        var nullabilityInfo = nullabilityContext.Create(property);
        //        if (nullabilityInfo.ReadState == NullabilityState.Nullable)
        //        {
        //            continue;
        //        }

        //        // 获取当前属性在 carrierDTO 对象上的值
        //        var value = property.GetValue(entity);
        //        var fieldAttr = property.GetCustomAttribute<FieldMetadataAttribute>();
        //        // 如果值不为空，进行验证
        //        if (value == null)
        //        {
        //            //判断是否标记了 FieldMetadataAttribute ，如果指定了label，取label值
        //            var propertyLabel = property.Name;
        //            if (fieldAttr != null)
        //            {
        //                if (string.IsNullOrEmpty(fieldAttr.Label))
        //                {
        //                    propertyLabel = fieldAttr.Label;
        //                }
        //            }

        //            errMsg = $"{propertyLabel} 不能为空";
        //            return false;
        //        }
        //        else if (fieldAttr != null && property.PropertyType == typeof(string))
        //        {
        //            if (fieldAttr.IsNotNullString && string.IsNullOrEmpty(value.ToString()))
        //            {
        //                errMsg = $"{fieldAttr.Label} 不能为空";
        //                return false;
        //            }
        //        }
        //    }

        //    return true;
        //}
    }
}
